package service

import (
	"context"

	aiv1 "github.com/devops-smartbot/devops-smartbot/proto/gen/go/ai/v1"
	"github.com/devops-smartbot/devops-smartbot/services/ai-gateway/internal/provider"
)

// Service defines AI orchestration behaviour.
type Service interface {
	Analyze(ctx context.Context, req *aiv1.AnalyzeRequest) (*aiv1.AnalyzeResponse, error)
}

// New creates a new service with provider registry.
func New(registry provider.Registry) Service {
	return &svc{registry: registry}
}

type svc struct {
	registry provider.Registry
}

func (s *svc) Analyze(ctx context.Context, req *aiv1.AnalyzeRequest) (*aiv1.AnalyzeResponse, error) {
	providerName := req.GetProvider()
	if providerName == "" {
		providerName = provider.TypeOpenAI
	}
	backend, err := s.registry.Resolve(providerName)
	if err != nil {
		return nil, err
	}

	resp, err := backend.Analyze(ctx, provider.Request{
		Prompt:   req.GetPrompt(),
		Metadata: req.GetMetadata(),
	})
	if err != nil {
		return nil, err
	}

	return &aiv1.AnalyzeResponse{
		Output:     resp.Content,
		LatencyMs:  resp.LatencyMs,
		Cost:       resp.Cost,
		Metadata:   resp.Metadata,
	}, nil
}

var _ Service = (*svc)(nil)
